import ccxt
import ccxt.pro
from common.variables import proxies
from functools import lru_cache
import toml


with open("./config.toml") as f:
    accounts = toml.load(f)


@lru_cache(1)
def get_binance_future_mock_exchange() -> ccxt.binance:
    exchange_name = "binance"
    account = "demo1"
    # account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "options": {
                "defaultType": "future",  # 确保连接到期货市场
                # 'portfolioMargin': True
            },
        }
    )
    exchange.https_proxy = proxies["https"]
    exchange.set_sandbox_mode(True)
    return exchange


@lru_cache(1)
def get_binance_portfolio_exchange() -> ccxt.binance:
    exchange_name = "binance"
    # account = "demo1"
    account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "options": {
                # 'defaultType': 'future',
                "portfolioMargin": True
            },
        }
    )
    exchange.https_proxy = proxies["https"]
    return exchange


@lru_cache(1)
def get_async_binance_portfolio_exchange() -> ccxt.pro.binance:
    exchange_name = "binance"
    # account = "demo1"
    account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.pro.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "https_proxy": proxies["https"],
            "options": {"defaultType": "margin", "portfolioMargin": True},
        }
    )
    # exchange.https_proxy = proxies["https"]
    exchange.ws_proxy = proxies["https"]
    return exchange


# @lru_cache(1)
def get_async_binance_portfolio_exchange_no_key() -> ccxt.pro.binance:
    exchange = ccxt.pro.binance(
        {
            "timeout": 300000,
            "https_proxy": proxies["https"],
            "options": {"defaultType": "margin", "portfolioMargin": True},
        }
    )
    exchange.ws_proxy = proxies["https"]
    return exchange
